package at.main.android;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Random;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.util.Log;
import android.widget.Toast;

public class Utils {

	public static final boolean         DEBUG_ENABLED                       = true;
    public static final boolean         FORCE_UNLOCK                        = false;
    public static final boolean         FORCE_SMS_BUY                       = false;

    // Application Preferences (Records)
    // Handle save/load in a separated class
    public static final String          PREFERENCES_NAME                    = "SMSWrapperPreferences";
    public static final String          PREFERENCES_SELECTED_PROFILE        = "PREFERENCES_SELECTED_PROFILE";
    public static final String          PREFERENCES_UNIQUE_NUMBER           = "PREFERENCES_UNIQUE_NUMBER";
    public static final String          PREFERENCES_GAME_UNLOCKED           = "PREFERENCES_GAME_UNLOCKED";
    public static final String          PREFERENCES_CURRENT_VIEW            = "PREFERENCES_CURRENT_VIEW";
    public static final String          PREFERENCES_DEMO_TIMES_REMAINING    = "PREFERENCES_DEMO_TIMES_REMAINING";
    public static final String          PREFERENCES_SMS_WAS_SENT            = "PREFERENCES_SMS_WAS_SENT";
    public static final String          PREFERENCES_SELECTED_LANGUAGE       = "PREFERENCES_SELECTED_LANGUAGE";

    private static Context              currentContext                      = null;
	
	public static final int DETECT_COUNTRY_FAILED = -1;
    
    static final int MAX_UNLOCK_CODE = 9999;
    static final int MIN_UNLOCK_CODE = 1111;

	static HashMap<String, Long> mTimers = new HashMap<String, Long>();
	
	public static final String[] ISO2Languages =
	{
		"EN",
		"FR",
		"DE",
		"SP",
		"IT"
	};
	
	public static final int TOTAL_LANG = 5;

	public static void initTimer(String key)
	{
		if(mTimers.containsKey(key))
			mTimers.remove(key);

		Long time = new Long(System.currentTimeMillis());
		mTimers.put(key, time);
	}
	
	public static long endTimer(String key)
	{

		if(mTimers.containsKey(key))
		{
			long time = Long.valueOf(mTimers.get(key));
			time = System.currentTimeMillis()-time;
			Log.d("Utils",key+" "+time);
			return time;
		}
		Log.d("Utils","FOUND NOT TIMER "+key);
		return 0;
	}

	public static void showDialog(Context context, String text, int time){
		Toast.makeText(context , text, time).show();
	}
	public static void showDialog(Context context, String text){
		Toast.makeText( context, text, Toast.LENGTH_SHORT).show();
	}


	
	

    /**
    * Set the current and save it into currentContext
    * @param  context the context from the application
    */
    public static void setContext(Context context)
    {
        currentContext = context;
    }

    /**
    * Get the current context
    * @param  context the context from the application
    * @return an Context object
    */
    public static Context getContext()
    {
        if (currentContext == null)
        {
            log("getContext(): currentContext is null! Have you called setContext() first?");
        }
        return currentContext;
    }

    /**
    * Open an asset file using a streaming mode.
    * @param  fileName the asset to open
    * @return an InputStream
    */
    public static InputStream getResourceAsStream(String fileName)
    {
        AssetManager am = currentContext.getAssets();
        InputStream is = null;

        try
        {
           is = am.open(fileName);
		   // is = new FileInputStream(SD_FOLDER + "/" + fileName);
		   // is = new FileInputStream(fileName);
		   //is = currentContext.getResources().openRawResource(fileName);
		   //is = this.getClass().getResourceAsStream("/profiles");
        }
		catch (FileNotFoundException e)
        {
            log(e);
        }
        catch (IOException e)
        {
            log(e);
        }
        return is;
    }

    /**
    * Read a text file in the specified encoding, and return a String array
    * with each line as a new element.
    * @param  fileName the asset to open
    * @return an InputStream
    */
    public static String[] readTextFile(String fileName, String encoding)
    {
        String strTextFileInOneString = null;
        String [] strTextFileInStringArray = null;
		BufferedReader reader = null; 
		String s = ""; 
        // InputStream is = Utils.getResourceAsStream(fileName);
        try
        {
		/*
            byte[] data = new byte[is.available()];
            is.read(data);
            strTextFileInOneString = new String(data, encoding);
            is.close();*/
			// f = new File("/sdcard/gameloft/games/asphalt5/profiles");
			reader = new BufferedReader(new FileReader("/sdcard/gameloft/games/asphalt5/profiles")); 
			while(((s = reader.readLine()) != null) ) 
			{
				strTextFileInOneString+=s+"\n";
			}

			
        }
        catch (Exception e)
        {
            log(e);
        }

        if (strTextFileInOneString != null)
        {
            strTextFileInStringArray = strTextFileInOneString.split("\n");
        }
        return strTextFileInStringArray;
    }

    /**
    * Print the specified message when DEBUG_ENABLED is true
    * @param  o the object to output
    */
    public static void log(Object o)
    {
        if (DEBUG_ENABLED)
        {
            if (o == null)
            {
                Log.d("SMSWrapper", "can't log o, is null");
                return;
            }
            if(o instanceof Exception)
            {
                Log.d("SMSWrapper", o.toString(),(Exception)o);
            }
            else
            {
                Log.d("SMSWrapper", o.toString());
            }
        }
    }

    /**
    * Make the button gray and non functional
    * @param button the button do disable
    */
    /*
    public static void disableButton(Button button)
    {
        Drawable back = getContext().getResources().getDrawable(R.drawable.button_background_disabled);
        button.setBackgroundDrawable(back);
        button.setTextColor(Color.GRAY);
        button.setOnClickListener(null);
    }
	*/
    /**
    * Set a Shared Preference from the application
    * @param key the key in a String representation
    * @param value the value to store in an Object instance
    */
    public static void setPreference(String key, Object value)
    {
        SharedPreferences settings = currentContext.getSharedPreferences(PREFERENCES_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();

        if (value instanceof String)
        {
            editor.putString(key, (String) value);
        }
        else if (value instanceof Integer)
        {
            editor.putInt(key, (Integer) value);
        }
        else if (value instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) value);
        }
        editor.commit();
    }

    public static String getPreferenceString(String key)
    {
        SharedPreferences settings = currentContext.getSharedPreferences(PREFERENCES_NAME, 0);
        return settings.getString(key, "");

    }

    public static int getPreferenceInt(String key)
    {
        if( key.equalsIgnoreCase(PREFERENCES_UNIQUE_NUMBER))
        {
			/*int code = getUniqueCode(MIN_UNLOCK_CODE, MAX_UNLOCK_CODE);
            if(code == getPreferenceInt(key, getUniqueCode(MIN_UNLOCK_CODE, MAX_UNLOCK_CODE)))
				setPreference(key, code);*/
			return getPreferenceInt(key, getUniqueCode(MIN_UNLOCK_CODE, MAX_UNLOCK_CODE));
        }
        else
        {
            return getPreferenceInt(key, -1);
        }
    }

    public static int getPreferenceInt(String key, int defaultValue)
    {
        SharedPreferences settings = currentContext.getSharedPreferences(PREFERENCES_NAME, 0);
        return settings.getInt(key, defaultValue);
    }

    public static boolean getPreferenceBoolean(String key)
    {
        return getPreferenceBoolean(key, false);
    }

    public static boolean getPreferenceBoolean(String key, boolean defaultValue)
    {
        SharedPreferences settings = currentContext.getSharedPreferences(PREFERENCES_NAME, 0);
        return settings.getBoolean(key, false);
    }

    /**
    *  Returns a random number in a range between minNumber and maxNumber
    *  @param minNumber the minimum value that the random can be
    *  @param maxNumber the maximum value that the random can be
    */
    public static int getUniqueCode(int minNumber, int maxNumber)
    {
        double rnd = new Random().nextDouble();
        int randomNumber = (int)(((maxNumber - minNumber + 1) * rnd ) + minNumber );

        return randomNumber;
    }


    /**
    * used for debug proposes only
    * Set all to default
    */
    /*
    public static void reset()
    {
        if(!DEBUG_ENABLED)
        {
            return;
        }
        log("Reset!");
        try {
            setPreference(PREFERENCES_DEMO_TIMES_REMAINING, SMSWrapper.MAX_DEMO_ATTEMPTS);
            setPreference(PREFERENCES_GAME_UNLOCKED, false);
            setPreference(PREFERENCES_SELECTED_LANGUAGE, "");
            setPreference(PREFERENCES_SELECTED_PROFILE, "");
            setPreference(PREFERENCES_SMS_WAS_SENT, false);
            setPreference(PREFERENCES_UNIQUE_NUMBER, -1);
            setPreference(PREFERENCES_CURRENT_VIEW, SMSModel.getDefaultLayout());
        } catch (Exception e) {
            Utils.log(e);
        }
    }*/

    public static String[] objectArrayToStringArray(Object[] o)
    {
        String[] strArray = new String[o.length];
        for (int i = 0; i < strArray.length; i++)
        {
            if (o[i] == null)
                continue;
            strArray[i] = o[i].toString();
        }
        return strArray;
    }

    public static void logWindowMessage(Context baseContext, String string) {
        if(DEBUG_ENABLED){
            Toast.makeText(baseContext, string, Toast.LENGTH_SHORT).show();
        }
    }
	
	public static int getDetectLang()
	{
		String DeLang = Locale.getDefault().getLanguage().toUpperCase();
		for(int i = 0; i < TOTAL_LANG; i++)
			if(ISO2Languages[i].equals(DeLang))
				return i;
				
		return -1;
	}
	
	
	
}

